<?php
$host = 'localhost'; // Database Host
$dbname = 'tony11'; // Database Name
$username = 'tony11'; // Database Username
$password = '123'; // Database password
$table_name = 'rank'; // Table Name

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');// 允許所有來源

try {
  $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $nickname = $input['nickname'] ?? null;
    $score = $input['score'] ?? null;
    $time = $input['time'] ?? null;

    if ($nickname && $score && $time) {
      $stmt = $pdo->prepare("INSERT INTO {$table_name} (nickname, score, time) VALUES (:nickname, :score, :time)");
      $stmt->execute([
        ':nickname' => $nickname,
        ':score' => $score,
        ':time' => $time,
      ]);

      echo json_encode(['status' => 'success', 'message' => 'Data saved successfully!'], JSON_UNESCAPED_UNICODE);
    } else {
      echo json_encode(['status' => 'error', 'message' => 'Invalid input.']);
    }
  } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $pdo->query("SELECT * FROM {$table_name}");
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($results);
  } else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
  }
} catch (PDOException $e) {
  echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
